package com.usian.controller;

import com.usian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RequestMapping("/user")
@RestController
public class ConsumerController {

    //获取服务端的ip，调用的服务
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //原生服务调用
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getUserBy")
    public ResponseEntity<User> getUserBy(@PathVariable Integer id){
        //调用服务
        ServiceInstance si=loadBalancerClient.choose("Nacos_provider");
        //拼接请求地址
        String url="http://"+si.getHost()+":"+si.getPort()+"/user/findById/"+id;
        //发起请求
        return restTemplate.getForEntity(url,User.class);
    }
}
